package xyz.msj.hrm.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.msj.hrm.doc.CourseDocument;
import xyz.msj.hrm.domain.Course;
import xyz.msj.hrm.domain.CourseDetail;
import xyz.msj.hrm.domain.CourseMarket;
import xyz.msj.hrm.domain.CourseResource;
import xyz.msj.hrm.dto.CourseDTO;
import xyz.msj.hrm.feign.client.CourseFeignClient;
import xyz.msj.hrm.feign.client.MQFeignClient;
import xyz.msj.hrm.mapper.CourseDetailMapper;
import xyz.msj.hrm.mapper.CourseMapper;
import xyz.msj.hrm.mapper.CourseMarketMapper;
import xyz.msj.hrm.mapper.CourseResourceMapper;
import xyz.msj.hrm.query.CourseQuery;
import xyz.msj.hrm.service.ICourseService;
import xyz.msj.hrm.util.AjaxResult;
import xyz.msj.hrm.vo.SendEmailVO;
import xyz.msj.hrm.vo.SendSMSVO;
import xyz.msj.hrm.vo.SendSystemMessageVO;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mushengjie
 * @since 2020-09-11
 */
@Service
@Transactional
@Slf4j
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {
    @Value("${hrm.fastdfs.url}")
    private String fastUrl;
    //mqfeign接口
    @Autowired
    private MQFeignClient mqFeignClient;
    //fastdfs url

    //课程详细
    @Autowired
    private CourseDetailMapper courseDetailMapper;
    //课程市场
    @Autowired
    private CourseMarketMapper courseMarketMapper;
    //feign的接口
    @Autowired
    private CourseFeignClient courseFeignClient;
    //资源
    @Autowired
    private CourseResourceMapper courseResourceMapper;

    /**
     * 保存新添加的课程
     *
     * @param courseDTO
     */
    @Override
    public void saveOrUpdate(CourseDTO courseDTO) {

        //获取课程对象
        Course course = courseDTO.getCourse();
        //获取课程详细对象
        CourseDetail courseDetail = courseDTO.getCourseDetail();
        //获取课程市场对象
        CourseMarket courseMarket = courseDTO.getCourseMarket();
        //判断参数值 判断所有参数
        if (StringUtils.isEmpty(course.getName())) {
            throw new RuntimeException("课程名不能为空");
        }
        if (course.getCourseTypeId() == null) {
            throw new RuntimeException("课程id不能为空");
        }
        //保存课程对象返回id
        //设置状态为上线,默认下线
        course.setStatus(Course.COURSE_OFF_STATE);
        //设置用户id
        course.setUserId(42L);
        //设置用户名
        course.setUserName("yhptest1");
        //设置公司id
        course.setTenantId(26L);
        //设置公司名
        course.setTenantName("源码时代");
        course.setSaleCount(0);
        course.setViewCount(0);
        course.setCommentCount(0);
        course.setPic(fastUrl + course.getPic());
        //保存
        baseMapper.insert(course);

        //保存营销
        //设置是否有效 默认有效
        courseMarket.setValid(CourseMarket.VALID);
        //设置id
        courseMarket.setId(course.getId());
        courseMarketMapper.insert(courseMarket);
        //保存详情
        //设置id
        courseDetail.setId(course.getId());
        courseDetailMapper.insert(courseDetail);
    }

    /**
     * 课程上线
     *
     * //1.根据ID查询Mysql中的课程
     * //2.判断课程状态为下线才能上线
     * //3.修改课程的状态为上线
     * //4.保存修改的课程到Mysql
     * //5.保存课程到ES
     * //5.1.为search-server编写ES的controller添加数据
     * //5.2.为search-server编写Feign接口
     * //5.3.考虑吧course对象转成courseDoc对象
     * //5.4.course-server集成并调用ES的Feign，完成数据的存储
     * @param id
     */
    @Override
    public void onLineCourse(Long id) throws Exception {
        //1.根据ID查询Mysql中的课程
        Course course = baseMapper.selectById(id);
        //2.判断课程状态为下线才能上线
        if (course == null || course.getStatus()==Course.COURSE_ON_STATE){
            log.error("课程不存在或者课程已经上线");
            throw new RuntimeException("课程不存在或者课程已经上线！");
        }
        //3.修改课程的状态为上线
        course.setStatus(Course.COURSE_ON_STATE);
        //4.保存修改的课程到Mysql
        baseMapper.updateById(course);
        //5.保存课程到ES
        //5.1.为search-server编写ES的controller添加数据
        //课程营销
        CourseMarket courseMarket = courseMarketMapper.selectById(id);
        //详细信息
        CourseDetail courseDetail = courseDetailMapper.selectById(id);

        //文档映射对象
        CourseDocument courseDocument = new CourseDocument();

        //属性复制
        BeanUtils.copyProperties(course,courseDocument);
        BeanUtils.copyProperties(courseMarket,courseDocument);
        BeanUtils.copyProperties(courseDetail,courseDocument);

        courseDocument.setOnLineTime(new Date());
        courseDocument.setSearchField(new StringBuffer()
                .append(course.getName())
                .append(courseDetail.getDescription())
                .append(course.getTenantName()).toString());

        //保存到ES
        AjaxResult ajaxResult = courseFeignClient.save(courseDocument);

        //失败
        if(!ajaxResult.isSuccess()){
            log.error("课程上线到ES失败");
            throw new RuntimeException("课程上线到ES失败");
        }

       //发送课程publishMessage推广信息
        publishMessage(course.getName());
    }

    /**
     * 发送课程publishMessage推广信息
     * @param
     */
    private void publishMessage(String courseName) {
        //发送短信
        String SMSMessage = "尊敬的用户我们的新课程" + courseName + "已经上线了，期待能得观看！";
        SendSMSVO sendSMSVO = new SendSMSVO("18482203513", SMSMessage);
        //调用mqfeign接口
        AjaxResult SMSAjaxResult = mqFeignClient.sendSMS(sendSMSVO);
        if (!SMSAjaxResult.isSuccess()) {
            log.error("发送短信失败！");
        }


        //发送邮件
        String emailMessage = "尊敬的用户我们的新课程" + courseName + "已经上线了，期待能得观看！";
        SendEmailVO sendEmailVO = new SendEmailVO("110@qq.com", emailMessage);
        //调用mqfeign接口
        AjaxResult emailAjaxResult = mqFeignClient.sendEmail(sendEmailVO);
        if (!emailAjaxResult.isSuccess()) {
            log.error("发送邮件失败！");
        }
        //发送短信
        String systemMsgSMessage = "尊敬的用户我们的新课程" + courseName + "已经上线了，期待能得观看！";
        String title = "SpringClod从小白的大神";
        SendSystemMessageVO sendSystemMessageVO = new SendSystemMessageVO(new Date(), 1L,title,systemMsgSMessage);
       //调用mqfeign接口
        AjaxResult systemAjaxResult = mqFeignClient.sendSystemMessage(sendSystemMessageVO);
        if (!systemAjaxResult.isSuccess()) {
            log.error("发送系统消息失败！");
        }
    }

    /**
     * 课程下线
     *
     * @param id
     */
    @Override
    public void offLineCourse(Long id) {

        //1.根据ID查询Mysql中的课程
        Course course = baseMapper.selectById(id);
        //2.判断课程状态为上线才能下线
        if (course == null || course.getStatus()==Course.COURSE_OFF_STATE){
            log.error("课程不存在或者课程已经下线");
            throw new RuntimeException("课程不存在或者课程已经下线！");
        }
        //3.修改课程的状态为下线
        course.setStatus(Course.COURSE_OFF_STATE);
        //4.保存修改的课程到Mysql
        baseMapper.updateById(course);

        //文档映射对象
        CourseDocument courseDocument = new CourseDocument();
        //获得id
        courseDocument.setId(course.getId());

        //删除es
        AjaxResult ajaxResult = courseFeignClient.delete(courseDocument);

        //失败
        if(!ajaxResult.isSuccess()){
            log.error("课程下线删除ES失败");
            throw new RuntimeException("课程下线删除ES失败");
        }
    }

    /**
     * 上传资源
     *
     * @param param
     */
    @Override
    public void addPhoto(Map<String, String> param) {



        //获取课程id
        Long courseId = Long.valueOf(param.get("id"));
        //获取课程资源路径
        String fileLoad = param.get("fileLoad");
        //判断参数
        if (courseId == null){
            throw new RuntimeException("课程id为空");
        }
        if (StringUtils.isEmpty(fileLoad)){
            throw new RuntimeException("课程资源为空");
        }

        //对传入的字符串进行分割
        String[] filePaths = fileLoad.split(",");
        for (String filePath : filePaths) {
            //创建资源对象
            CourseResource courseResource = new CourseResource();
            //设置地址fastdfs
            courseResource.setResources(filePath);
            courseResource.setCourseId(courseId);
            //保存
            courseResourceMapper.insert(courseResource);
        }

    }

    /**
     * 根据条件查询课程对象
     *
     * @param courseQuery
     */
    @Override
    public AjaxResult queryCourses(CourseQuery courseQuery) {

        return courseFeignClient.search(courseQuery);
    }
}
